<template>
  <div class="app-container">
    <div class="form-container">
          <el-form ref="searchForm" :model="searchForm" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="缴费人" prop="stuName">
                        <el-input v-model="searchForm.stuName" placeholder="请输入缴费人姓名"/>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="业务类型" prop="proId">
                        <el-select clearable v-model="searchForm.proId" placeholder="请选择业务类型">
                            <el-option v-for="item in products" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                  <el-col :span="5">
                    <el-form-item label="订单状态" prop="status">
                        <el-select clearable v-model="searchForm.status" placeholder="请选择订单状态">
                            <el-option label="正常" value="1"></el-option>
                            <el-option label="即将到期" value="2"></el-option>
                            <el-option label="到期" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="经办人" prop="admId">
                        <el-select clearable v-model="searchForm.admId" placeholder="请选择创建人">
                            <el-option v-for="item in admins" :key="item.id" :label="item.username" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button icon="el-icon-search" type="primary" circle @click="getData" />
                  <el-button icon="el-icon-refresh-right" type="warning" size="medium" round @click="resetForm('searchForm')">
                      重置
                    </el-button>
              </el-col>
            </el-row>
        </el-form>
    </div>

    <div class="action">
      <el-button icon="el-icon-plus" type="primary" size="small" round @click="handleAdd">
          新建
      </el-button>
    </div>

    <el-table stripe border fit highlight-current-row
    :header-cell-style="{textAlign: 'center'}"
     :cell-style="{ textAlign: 'center' }"
    :data="orders.slice((page - 1) * limit, page * limit)" style="width: 100%">
    
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="客户ID">
              <span>{{ props.row.student.id }}</span>
            </el-form-item>
            <el-form-item label="创建人ID">
              <span>{{ props.row.admin.id }}</span>
            </el-form-item>
            <el-form-item label="客户姓名">
              <span>{{ props.row.student.username }}</span>
            </el-form-item>
            <el-form-item label="创建人姓名">
              <span>{{ props.row.admin.username }}</span>
            </el-form-item>
            <el-form-item label="客户性别">
              <span>{{ props.row.student.sex == 0 ? '男': '女' }}</span>
            </el-form-item>
            <el-form-item label="创建人性别">
              <span>{{ props.row.admin.sex == 0 ? '男': '女'}}</span>
            </el-form-item>
            <el-form-item label="客户生日">
              <span>{{ $dayjs(props.row.student.birth).format('YYYY-MM-DD') }}</span>
            </el-form-item>
            <el-form-item label="创建人生日">
              <span>{{ $dayjs(props.row.admin.birth).format('YYYY-MM-DD') }}</span>
            </el-form-item>
            <el-form-item label="客户专业">
              <span>{{ props.row.student.username }}</span>
            </el-form-item>
            <el-form-item label="创建人邮箱">
              <span>{{ props.row.admin.email }}</span>
            </el-form-item>
            <el-form-item label="客户类型">
              <span>{{ props.row.student.level.name }}</span>
            </el-form-item>
            <el-form-item label="创建人类型">
              <span>{{ props.row.admin.role.name }}</span>
            </el-form-item>
            <el-form-item label="客户手机号">
              <span>{{ props.row.student.phoneNum }}</span>
            </el-form-item>
              <el-form-item label="创建人手机">
              <span>{{ props.row.admin.phoneNum }}</span>
            </el-form-item>
            <el-form-item label="客户状态">
              <span>{{ props.row.student.isEnable == 0 ? '禁用': '正常' }}</span>
            </el-form-item>
            <el-form-item label="创建人状态">
              <span>{{ props.row.admin.isEnable == 0 ? '禁用': '正常'}}</span>
            </el-form-item>
            <el-form-item label="客户地址">
              <span>{{ props.row.student.address }}</span>
            </el-form-item>
            <el-form-item label="创建人地址">
              <span>{{ props.row.admin.address }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="ID" prop="id" width="80"/>
      <el-table-column label="业务名称" prop="product.name"/>
      <el-table-column label="缴费人" prop="student.username"/>
      <el-table-column label="缴费类型" prop="student.level.name"/>

      <el-table-column label="创建时间" prop="createTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近缴费时间" prop="renewTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.renewTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" prop="endTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.endTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" prop="isEnable"  label="状态" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.endTime | statusFilter(that)">
              {{ formatterStatus(row.endTime)}}
            </el-tag>
          </template>
        </el-table-column>

      <el-table-column label="总费用 (元)" prop="totalMoney"/>
      <el-table-column label="经办人" prop="admin.username"/>

      <el-table-column label="操作"  min-width="120px">
          <template slot-scope="scope">
            <el-button type="primary" title="编辑" icon="el-icon-edit" size="small" circle @click="handleEdit(scope.row)"/>
            <el-button type="warning" title="续费" icon="iconfont icon-renew" size="small" circle @click="handleRenew(scope.row)"/>
            <el-button type="danger" title="删除" icon="el-icon-delete" size="small" circle @click="handleDelete(scope.row)"/>
          </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getData"/>
  </div>

</template>

<script>
import Pagination from "@/components/Pagination";



export default {
  components: { Pagination },
  filters: {
    statusFilter(endTime,that) {
      const statusMap = { 0: 'danger', 1: 'success',2:'warning'}
      let status
      if(that.nowTime.getTime() - endTime > 0 )  {
          status = 0
      }else if((endTime - that.nowTime.getTime())/(1000*60*60*24) <= 7){
          status = 2
      }else{
          status = 1
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      products:[],
      admins:[],
      orders:[],
      total: 0,
      listLoading: true,
      page: 1,
      limit: 5,
      searchForm: {
        stuName: "",
        proId:"",
        status:"",
        admId:''
      },
      nowTime:'',
      that:this,
    };
  },
  methods: {
    async getData() {
      this.nowTime = new Date()
      let res = await this.$store.dispatch('order/getList',this.searchForm) 
      if(res.code == 1) {
          console.log(res.data);
          this.orders = res.data 
          this.total = this.orders.length 
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
      // 获取产品列表
      res = await this.$store.dispatch('dataBase/getProductList') 
      if(res.code == 1) {
          this.products = res.data
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
      // 获取管理员列表 添加参数
      res = await this.$store.dispatch('admin/getList',{username:'',sex:'',roleId:'',status:''}) 
      if(res.code == 1) {
          this.admins = res.data
      }else{
          this.$message({ showClose: true,message: res.msg, type: 'error'})
      }
      
    },
    handleEdit({id}) {
      this.$router.push({path:"/order/edit",query: {id}},)
    },
    handleRenew({id}){
      console.log("续费"+id);
      // 根据 id 寻找数据在 数组中的 下标
      const index = this.orders.map(item => item.id).indexOf(id)
      // 获取客户类型
      const {student} = this.orders[index]
      const {username ,level} = student
      let msg =''
      if(level.name == '包月客户') {
        msg = id+ " "+" 客户姓名: "+ username +  ' 充值 '+level.price+' 元 即增加一个月的时间'
      }else{
        msg = id+ " "+" 客户姓名: "+ username +  ' 充值 '+level.price+' 元 即增加一年的时间'
      }
      this.$confirm("此操作将为订单ID为 " +msg+ ", 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(async () => {
 
          const res = await this.$store.dispatch('payment/addPayment',{orderId:id,money:level.price}) 
          if(res.code == 1) {
            // 数据库的总费用修改成功 将表格的总费用修改
            // 根据 id 寻找数据在 数组中的 下标
            const index = this.orders.map(item => item.id).indexOf(id)
            let price = this.orders[index].student.level.price
            // 修改总费用
            this.orders[index].totalMoney = this.orders[index].totalMoney+price
          

            // 修改到期时间 生成date 对象
              let endTime = new Date(this.orders[index].endTime)
            if(price == 300) {
               // 续一年
              this.orders[index].endTime =endTime.setFullYear( endTime.getFullYear() +1)
                       
            }else{
              // 续一月             
              this.orders[index].endTime=  endTime.setMonth( endTime.getMonth() + 1 )
            }

            // 修改最近充值时间
            let now = new Date()
            this.orders[index].renewTime = now

            this.$message({ type: "success",  message: res.msg, duration: 1000});
          }else{
            this.$message({ type: "error",  message: res.msg, duration: 1000});
          }
      })
      .catch(() => {
        this.$message({ type: "info", message: "已取消续费"});
      });
    },
    handleDelete({id}) {
      // console.log("删除"+id);
      this.$confirm("此操作将永久删除ID为 "+id+" 订单信息及充值记录信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(async () => {
          const res = await this.$store.dispatch('order/deleteOrder',id) 
          if(res.code == 1) {
               // 根据 id 寻找数据在 数组中的 下标
              const index = this.orders.map(item => item.id).indexOf(id)
              // 删除这一行
              this.orders.splice(index,1)
              // 数组长度减 1 动态绑定到分页器
              this.total--;
              this.$message({ type: "success",  message: res.msg, duration: 1000});
          }else{
              this.$message({ type: "error",  message: res.msg, duration: 1000});
          }
      })
      .catch(() => {
        this.$message({ type: "info", message: "已取消删除"});
      });

    },
    handleAdd() {
      this.$router.push({path:"/order/add"})
    },
    resetForm(searchForm) {
      this.$refs[searchForm].resetFields()
      this.$message({ showClose: true, message: '清空成功', type: 'success' })
    },
    formatterStatus(endTime) {
      let status
      if(this.nowTime.getTime() - endTime > 0 )  {
          status = '到期'
      }else if((endTime - this.nowTime.getTime())/(1000*60*60*24) <= 7){
          status = '即将到期'
      }else{
          status = '正常'
      }
       
      return status
    }
  },
  mounted() {
    this.getData();
  }
};
</script>

<style lang="scss" scoped>
  .form-container {
    display: flex;
    width: 100%;
    align-items:center;
    justify-content:center;
  }
  .search {
    width: 100%;
    text-align: center;
    padding-left: 20px;
  }
  .search-more {
    width: 100%;
  }
  .action {
    width: 100%;
    padding-bottom: 10px;
    text-align: left;
  }
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 90px;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
